package ua.edu.nuos.jeetraining2012.cms.util.mail.course;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import ua.edu.nuos.jeetraining2012.cms.entity.CourseEntity;
import ua.edu.nuos.jeetraining2012.cms.util.LocaleWrapper;
import ua.edu.nuos.jeetraining2012.cms.util.mail.UserAbstract;

import java.io.IOException;
import java.io.StringWriter;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * Send Email notice to student about discarding him / her from course.
 *
 * @author Victor N. Ganichev victor.ganichev@gmail.com
 * @version 1.0 Date: 07.07.13 Time: 08:30
 * @since 1.0
 */
public class NotifyStudentDiscardedEnrollment extends UserAbstract {

    /** Define base URL */
    private String baseUrl;

    /** Define course data. */
    private CourseEntity course;

    /** Define ResourceBundle. */
    private ResourceBundle i18n;

    /** Define logger. */
    final private static Logger logger = org.slf4j.LoggerFactory.getLogger(NotifyStudentDiscardedEnrollment.class);

    // Constructor

    /**
     * Default constructor.
     */
    public NotifyStudentDiscardedEnrollment() {
        logger.debug("NotifyStudentDiscardedEnrollment invocation.");

        try {
            i18n = LocaleWrapper.getBundle("course");
        } catch (MissingResourceException e) {
            logger.error("Can't setup ResourceBundle. Error: {}", e.getMessage());
        }
    }

    // Getters & Setters
    public void setCourse(CourseEntity course) {
        this.course = course;
    }

    public void setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
    }


    // Actions
    @Override
    public String getSubject() {
        try {
            logger.debug("Defining email subject.");
            MessageFormat formatter = new MessageFormat("");
            formatter.setLocale(LocaleWrapper.getLocale());
            formatter.applyPattern(i18n.getString("notify_discarded_student_subject"));

            return formatter.format(new Object[] {
                    i18n.getString("notify_discarded_student_subject"),
                    course.getTitle()
            });

        } catch (MissingResourceException | NullPointerException e) {
            return "Інформація. Нажаль, ви не були стверджені інструктором для участі в курсі.";
        }
    }

    @Override
    public String getBodyMessage() {
        Map<String, Object> dataMap = new HashMap<>();

        MessageFormat formatter = new MessageFormat("");
        formatter.setLocale(LocaleWrapper.getLocale());
        formatter.applyPattern(i18n.getString("notify_discarded_student_body"));

        logger.debug("Forming notification mail about user {} enrollment to course {}", userEntity.getId(), course.getId());
        try {
            dataMap.put("noticeBody", formatter.format(new Object[] {
                    i18n.getString("notify_discarded_student_body"),
                    course.getTitle(),
                    baseUrl
            }));

            Configuration cfg = getTemplateConfig();
            Template template = cfg.getTemplate("notifyDiscardedUserCourseEnrollment.ftl");
            StringWriter writer = new StringWriter();
            template.process(dataMap, writer);
            return writer.toString();
        } catch (IOException | TemplateException |
                MissingResourceException | NullPointerException e) {
            logger.error("getBodyMessage() Exception", e);
            return "Нажаль, ваша заявка не була схвалена інструктором, ви не взмозі приступити до навчання на курсі.";
        }
    }
}
